3 * Copyright © 2006-2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com",
4 * Daniel Cannon (cannon dot danielc at gmail dot com)
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Auth\AuthManager
;
25 use MediaWiki\Auth\AuthenticationRequest
;
26 use MediaWiki\Auth\AuthenticationResponse
;
27 use MediaWiki\Logger\LoggerFactory
;
30 * Unit to authenticate log-in attempts to the current wiki.
34 class ApiLogin
extends ApiBase
{
36 public function __construct( ApiMain
$main, $action ) {
37 parent
::__construct( $main, $action, 'lg' );
40 protected function getExtendedDescription() {
41 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
42 return 'apihelp-login-extended-description';
44 return 'apihelp-login-extended-description-nobotpasswords';
49 * Format a message for the response
50 * @param Message|string|array $message
51 * @return string|array
53 private function formatMessage( $message ) {
54 $message = Message
::newFromSpecifier( $message );
55 $errorFormatter = $this->getErrorFormatter();
56 if ( $errorFormatter instanceof ApiErrorFormatter_BackCompat
) {
57 return ApiErrorFormatter
::stripMarkup(
58 $message->useDatabase( false )->inLanguage( 'en' )->text()
61 return $errorFormatter->formatMessage( $message );
66 * Executes the log-in attempt using the parameters passed. If
67 * the log-in succeeds, it attaches a cookie to the session
68 * and outputs the user id, username, and session token. If a
69 * log-in fails, as the result of a bad password, a nonexistent
70 * user, or any other reason, the host is cached with an expiry
71 * and no log-in attempts will be accepted until that expiry
72 * is reached. The expiry is $this->mLoginThrottle.
74 public function execute() {
75 // If we're in a mode that breaks the same-origin policy, no tokens can
77 if ( $this->lacksSameOriginSecurity() ) {
78 $this->getResult()->addValue( null, 'login', [
79 'result' => 'Aborted',
80 'reason' => $this->formatMessage( 'api-login-fail-sameorigin' ),
86 $this->requirePostedParameters( [ 'password', 'token' ] );
88 $params = $this->extractRequestParams();
92 // Make sure session is persisted
93 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
96 // Make sure it's possible to log in
97 if ( !$session->canSetUser() ) {
98 $this->getResult()->addValue( null, 'login', [
99 'result' => 'Aborted',
100 'reason' => $this->formatMessage( [
101 'api-login-fail-badsessionprovider',
102 $session->getProvider()->describe( $this->getErrorFormatter()->getLanguage() ),
110 $context = new DerivativeContext( $this->getContext() );
114 $token = $session->getToken( '', 'login' );
115 if ( $token->wasNew() ||
!$params['token'] ) {
116 $authRes = 'NeedToken';
117 } elseif ( !$token->match( $params['token'] ) ) {
118 $authRes = 'WrongToken';
123 $authRes === false && $this->getConfig()->get( 'EnableBotPasswords' ) &&
124 ( $botLoginData = BotPassword
::canonicalizeLoginData( $params['name'], $params['password'] ) )
126 $status = BotPassword
::login(
127 $botLoginData[0], $botLoginData[1], $this->getRequest()
129 if ( $status->isOK() ) {
130 $session = $status->getValue();
131 $authRes = 'Success';
132 $loginType = 'BotPassword';
134 $status->hasMessage( 'login-throttled' ) ||
135 $status->hasMessage( 'botpasswords-needs-reset' ) ||
136 $status->hasMessage( 'botpasswords-locked' )
139 $message = $status->getMessage();
140 LoggerFactory
::getInstance( 'authentication' )->info(
141 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
144 // For other errors, let's see if it's a valid non-bot login
147 if ( $authRes === false ) {
148 // Simplified AuthManager login, for backwards compatibility
149 $manager = AuthManager
::singleton();
150 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
151 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
, $this->getUser() ),
153 'username' => $params['name'],
154 'password' => $params['password'],
155 'domain' => $params['domain'],
156 'rememberMe' => true,
159 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
160 switch ( $res->status
) {
161 case AuthenticationResponse
::PASS
:
162 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
163 $this->addDeprecation( 'apiwarn-deprecation-login-botpw', 'main-account-login' );
165 $this->addDeprecation( 'apiwarn-deprecation-login-nobotpw', 'main-account-login' );
167 $authRes = 'Success';
168 $loginType = 'AuthManager';
171 case AuthenticationResponse
::FAIL
:
172 // Hope it's not a PreAuthenticationProvider that failed...
174 $message = $res->message
;
175 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
176 ->info( __METHOD__
. ': Authentication failed: '
177 . $message->inLanguage( 'en' )->plain() );
181 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
182 ->info( __METHOD__
. ': Authentication failed due to unsupported response type: '
183 . $res->status
, $this->getAuthenticationResponseLogData( $res ) );
184 $authRes = 'Aborted';
189 $result['result'] = $authRes;
190 switch ( $authRes ) {
192 $user = $session->getUser();
194 ApiQueryInfo
::resetTokenCache();
198 Hooks
::run( 'UserLoginComplete', [ &$user, &$injected_html, true ] );
200 $result['lguserid'] = (int)$user->getId();
201 $result['lgusername'] = $user->getName();
205 $result['token'] = $token->toString();
206 $this->addDeprecation( 'apiwarn-deprecation-login-token', 'action=login&!lgtoken' );
213 $result['reason'] = $this->formatMessage( $message );
217 $result['reason'] = $this->formatMessage(
218 $this->getConfig()->get( 'EnableBotPasswords' )
219 ?
'api-login-fail-aborted'
220 : 'api-login-fail-aborted-nobotpw'
224 // @codeCoverageIgnoreStart
227 ApiBase
::dieDebug( __METHOD__
, "Unhandled case value: {$authRes}" );
228 // @codeCoverageIgnoreEnd
231 $this->getResult()->addValue( null, 'login', $result );
233 LoggerFactory
::getInstance( 'authevents' )->info( 'Login attempt', [
235 'successful' => $authRes === 'Success',
236 'loginType' => $loginType,
237 'status' => $authRes,
241 public function isDeprecated() {
242 return !$this->getConfig()->get( 'EnableBotPasswords' );
245 public function mustBePosted() {
249 public function isReadMode() {
253 public function getAllowedParams() {
257 ApiBase
::PARAM_TYPE
=> 'password',
261 ApiBase
::PARAM_TYPE
=> 'string',
262 ApiBase
::PARAM_REQUIRED
=> false, // for BC
263 ApiBase
::PARAM_SENSITIVE
=> true,
264 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-param-token', 'login' ],
269 protected function getExamplesMessages() {
271 'action=login&lgname=user&lgpassword=password'
272 => 'apihelp-login-example-gettoken',
273 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
274 => 'apihelp-login-example-login',
278 public function getHelpUrls() {
279 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login';
283 * Turns an AuthenticationResponse into a hash suitable for passing to Logger
284 * @param AuthenticationResponse $response
287 protected function getAuthenticationResponseLogData( AuthenticationResponse
$response ) {
289 'status' => $response->status
,
291 if ( $response->message
) {
292 $ret['message'] = $response->message
->inLanguage( 'en' )->plain();
295 'neededRequests' => $response->neededRequests
,
296 'createRequest' => $response->createRequest
,
297 'linkRequest' => $response->linkRequest
,
299 foreach ( $reqs as $k => $v ) {
301 $v = is_array( $v ) ?
$v : [ $v ];
302 $reqClasses = array_unique( array_map( 'get_class', $v ) );
304 $ret[$k] = implode( ', ', $reqClasses );